
//chatClient.c
//Ashish Tomar
//2009/1/27
//Network Security -- HW0


        #include "md5wrapper.h"
		# include <openssl/evp.h>
		#include <stdio.h>
		#include <string.h>
		#include <sys/types.h>
		#include <sys/socket.h>
		#include <netdb.h>
		#include <arpa/inet.h>
		#include <stdlib.h>
		#include <unistd.h>
		#include <errno.h>
		#include <netinet/in.h>
		#include <sys/wait.h>
		#include <signal.h>
		#include <pthread.h>
		#include <stdio.h>
		#include <pwd.h>
		#include <time.h>
		#include<ctype.h>
		#include <dirent.h>
		#include <sys/stat.h>
        #include <stdlib.h>
		#include <iostream>
		using namespace std;


#define MAXDATASIZE 2048

std::string getmd5(char *buf)
{
	md5wrapper md5;
	std::string ret="NULL";
	 ret=md5.getHashFromString(buf);
	 return ret;
}

void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) {
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}



int main(int argc, char *argv[])
{
		//declaration
		int sock, portNo;
		char *userName;
		int status;

		
		int sockfd, numbytes;  
		//char buf[MAXDATASIZE];
		char key[MAXDATASIZE];
		struct addrinfo hints, *servinfo, *p;
		int rv;
		unsigned char *keyy;
		unsigned char *iv;
		char s[INET6_ADDRSTRLEN];
unsigned char obuf[256];
	int olen,ilen,tlen;
	unsigned char keymaterial[256];
	int ic = 1000;
	 char *salt = "1234";
//char outbuf[1024];

 int outlen, tmplen;

		//declaration section end

		//main code
		if(argc!=4)
		{
				printf("This program requires 3 arguments ip adress, port no & username\n");
		}

		userName=argv[3];
		portNo=atoi(argv[2]);

		memset(&hints, 0, sizeof hints); // make sure the struct is empty
		hints.ai_family = AF_UNSPEC;     // don't care IPv4 or IPv6
		hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
		hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

		if ((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
			{
				printf( "getaddrinfo: %s\n", gai_strerror(status));
				return 1;
			}

		for(p = servinfo; p != NULL; p = p->ai_next) 
			{
				if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
				{
					perror("client: socket");
					continue;
				}

				if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
				{
					close(sockfd);
					perror("client: connect");
					continue;
				}

				break;
			 }

			if (p == NULL)
			{
				fprintf(stderr, "client: failed to connect\n");
				return 2;
			}

		inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
        printf("client: connecting to %s\n", s);

		freeaddrinfo(servinfo); // all done with this structure
		if (send(sockfd, argv[3], strlen(argv[3]), 0) == -1)
		perror("send");

char mess[MAXDATASIZE];
printf("\nPASS - ");
																			fflush(stdout);
					//char * mes;
					//gets(mess);
					cin.getline ( mess, MAXDATASIZE, '\n' );

					 if (send(sockfd, mess, strlen(mess), 0) == -1)
	{ perror("send");
	exit(1);
	}
//std::string md=getmd5(mess);
//cout<<"key is "<<md<<endl;


	PKCS5_PBKDF2_HMAC_SHA1(mess, strlen(mess), (unsigned char *)salt, strlen(salt), ic, 128, keymaterial);
keyy=keymaterial;
iv = keyy + 32;
//
/* if ((numbytes = recv(sockfd, key, MAXDATASIZE-1, 0)) == -1)
						{
							perror("recv");
							exit(1);
						 }
						 else
						{
								key[numbytes] = '\0';
								//if(numbytes >2)
								//decrypt buf using key
keyy=(unsigned char *)key;
iv = keyy + 32;

								printf("Key  Recieved \n");
							
						 }*/
//
char mes[MAXDATASIZE];
					//char * mes;
					unsigned char outbf[MAXDATASIZE];
					
				char *buf=(char *)malloc(2*MAXDATASIZE*sizeof(char));
			 unsigned	char *outbuf=(unsigned char *)malloc(2*MAXDATASIZE*sizeof(char));
   if(!fork())
	   {
			while(1)
				{
				
			//	char *buf=(char *)malloc(1024*sizeof(char));
			 //unsigned	char *outbuf=(unsigned char *)malloc(1024*sizeof(char));
						 if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
						{
							perror("recv");
							exit(1);
						 }
						 else
						{
								//buf[numbytes] = '\0';
								//if(numbytes >2)
								//decrypt buf using ke
								
								EVP_CIPHER_CTX ctx;
								EVP_CIPHER_CTX_init(&ctx);



 EVP_DecryptInit_ex(&ctx,EVP_aes_256_cbc(),NULL,keyy,iv);

 EVP_DecryptUpdate(&ctx,outbuf,&outlen,(unsigned char *)buf,numbytes);

 EVP_DecryptFinal_ex(&ctx,outbuf+outlen,&tmplen);

 outlen+=tmplen;

 EVP_CIPHER_CTX_cleanup(&ctx);



int t;
cout<<endl;
fflush(stdout);
for(t=0;t<outlen;t++){
											if(isalnum(outbuf[t])||ispunct(outbuf[t])||isspace(outbuf[t])||isdigit(outbuf[t]))
												{
																		if(t<outlen-3&&isspace(outbuf[t])&&isspace(outbuf[t+1])&&isspace(outbuf[t+2]))
																			{
																			printf("\n");
																			fflush(stdout);
																			break;
																			}
												
																		printf("%c",outbuf[t]);
																		fflush(stdout);
												}
												else{
													cout<<endl;
													fflush(stdout);
													break;
												}
										}

							//cout<<"--> "<<outbuf<<endl;
						 }
//free(buf);
//free(outbuf);

				}
   }
   
   else
	{
			while(1)
			{
					//char mes[MAXDATASIZE];
					//char * mes;
					//unsigned char outbf[MAXDATASIZE];
				//	gets(mes);
					 cin.getline ( mes, MAXDATASIZE, '\n' );
															int oul,tmpl;
															EVP_CIPHER_CTX ctx;

															EVP_CIPHER_CTX_init(&ctx);
															EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, keyy, iv);
															// EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, list[mm].passkey, list[mm].pass);
																



															if(!EVP_EncryptUpdate(&ctx, outbf, &oul,(unsigned char *) mes, strlen(mes)))
																{
																		/* Error */
																		return 0;
																}
														
															if (!EVP_EncryptFinal_ex(&ctx, outbf+oul, &tmpl)) {
																		return (0);
																	}
																	oul+=tmpl;


 EVP_CIPHER_CTX_cleanup(&ctx);




					//encrypt mes using key
					 if (send(sockfd, outbf, oul, 0) == -1)
				{	  perror("send");
exit(1);
				}
				//free(mes);
				//free(outbf);
			 }
	}

    close(sockfd);
		return 0;
}
